<template>
	<view class="pageview flex flex-direction">
		<view class="topwrap">
			<u-navbar title=" " :fixed="false" bgColor="transparent">
				<view slot="left"></view>
			</u-navbar>
			<view class="flex align-center justify-between welcome">
				<view class="name">
					Hi,欢迎
					<text class="text-bold">
						{{ userInfo.realName }}
					</text>
					来到慢病智慧管家
				</view>
			</view>
		</view>
		<!-- <view class="main flex-sub"> -->
		<scroll-view
			scroll-y="true"
			:refresher-enabled="true"
			:refresher-triggered="isRefreshing"
			refresher-background="transparent"
			@refresherrefresh="onPullRefresh"
			@scrolltolower="loadMore"
			:lower-threshold="threshold"
			class="scroll-view"
		>
			<!-- 下拉刷新区域的内容 -->
			<view class="u-m-l-20 u-m-r-20 calendarbox">
				<lx-calendar @change="changeDate" :dot_lists="daylist" :value="selectDay"></lx-calendar>
			</view>
			<view class="scheldule">
				<view v-for="(item, index) in schelduleList" :key="index" class="scheldule-item">{{ item.remark }}</view>
			</view>
			<!-- 当天任务 -->
			<view class="cu-title u-m-t-20">随访计划</view>
			<view class="userlist">
				<userItem :info="item" :index="index" v-for="(item, index) in planList" :key="index"></userItem>
				<mescroll-empty v-if="planList.length == 0"></mescroll-empty>
			</view>
			<!-- 加载状态 -->
			<view class="loading-status">
				<loading-indicator v-if="loading" animating />
				<text v-if="loading">加载中...</text>
				<text v-if="noMore" class="no-more">—— 没有更多数据了 ——</text>
				<text v-if="error" class="error" @click="retry">加载失败，点击重试</text>
			</view>
		</scroll-view>
		<!-- <u-back-top :scroll-top="scrollTop" top="100" z-index="9999" ></u-back-top> -->
		<u-back-top :scroll-top="scrollTop" @click="scrollToTop"></u-back-top>
		<!-- </view> -->
		<u-gap height="20"></u-gap>
	</view>
</template>

<script>
import mixin from '@/common/mixin.js';
import userItem from './components/userItem.vue';
import lxCalendar from '@/components/lx-calendar/lx-calendar.vue';
import dayjs from '@/utils/dayjs.min.js';
import { mapState, mapMutations } from 'vuex';
export default {
	mixins: [mixin],
	data() {
		return {
			planList: [],
			daylist: [],
			selectDay: '',
			today: dayjs().format('YYYY-MM-DD'),
			schelduleList: [],
			isRefreshing: true,
			pageNum: 0, // 当前页码
			pageSize: 10, // 每页数量
			loading: false, // 加载状态
			noMore: false, // 是否没有更多数据
			scrollHeight: 0, // scroll-view高度
			threshold: 100,
			scrollTop: 0
		};
	},
	components: {
		lxCalendar,
		userItem
	},
	computed: {
		...mapState(['curAccount', 'userInfo', 'accountList'])
	},
	created() {
		this.selectDay = dayjs().format('YYYY-MM-DD');
		this.getplanList();
		this.getSchelduleList();
	},
	onShow() {
		this.isShow = 1;
	},
	onHide() {
		this.isShow = 0;
	},
	onLoad() {},
	// 下拉刷新
	/* onPullDownRefresh() {
			console.log("到这里了嘛")
			if (this.userInfo.userId) {
				this.getplanList();
				this.getSchelduleList();
			}
			setTimeout(() => {
				uni.stopPullDownRefresh();
			}, 300);
		}, */

	methods: {
		...mapMutations(['$uStore']),
		// 下拉刷新
		onPullRefresh() {
			console.log('下拉刷新触发');
			this.isRefreshing = true;
			if (this.userInfo.userId) {
				this.pageNum = 0;
				this.noMore = false;
				this.getplanList();
				this.getSchelduleList();
			}
			// 模拟数据加载
			setTimeout(() => {
				this.isRefreshing = false;
			}, 300);
		},
		timeFormat(time) {
			if (time) {
				return this.$u.timeFormat(time, 'mm.dd');
			} else {
				return '--';
			}
		},
		changeDate(date) {
			this.selectDay = date.fulldate;
			this.pageNum = 0;
			this.noMore = false;
			this.getplanList();
			this.getSchelduleList();
		},
		navTo(path) {
			this.$Router.push(path);
		},

		getplanList() {
			this.pageNum++;
			let params = {
				/* scheduleId: '',
					ptime: this.selectDay, */
				pageNum: this.pageNum,
				pageSize: this.pageSize,
				realName: ''
			};
			if (this.loading || this.noMore) return;

			this.loading = true;
			this.error = false;

			try {
				this.$postAction(this.$api.getpatientList, params).then(da => {
					const items = da.list;
					if (!items || items.length === 0) {
						this.noMore = true;
						return;
					}

					// 如果是第一页，直接替换数据
					if (this.pageNum === 1) {
						this.planList = items;
					} else {
						// 否则追加数据
						this.planList = [...this.planList, ...items];
					}

					// 检查是否还有更多数据（根据API返回或数据条数判断）
					if (items.length < this.pageSize) {
						this.noMore = true;
					}
					this.$uStore({
						name: 'accountList',
						value: this.planList || []
					});
					let info = '';
					if (this.planList && this.planList.length > 0) {
						if (this.curAccount && this.curAccount.patientId) {
							info = this.planList.find(item => item.patientId == this.curAccount.patientId);
						}
						if (!info) {
							info = this.planList[0];
						}
					}
					// this.$uStore({
					// 	name: 'curAccount',
					// 	value: info
					// });
				});
				//this.planList = da;
				
			} catch (err) {
				console.error('加载数据失败:', err);
				this.error = true;
			} finally {
				this.loading = false;
				// this.isRefreshing = false;
			}
		},

		getListData(value) {
			let listData;
			let info = this.listData.find(item => item.date == value);
			if (info && info.scheduleVos) {
				return info.scheduleVos;
			}
			return [];
		},
		//获取日程
		getSchelduleList() {
			let year = this.selectDay.split('-')[0];
			let month = this.selectDay.split('-')[1];
			let day = this.selectDay.split('-')[2];
			let selectDate = year + '-' + parseInt(month) + '-' + parseInt(day);
			this.$postAction(this.$api.getSchelduleList, {
				month: month,
				year: year
			}).then(da => {
				console.log('数据' + JSON.stringify(da.length));
				let newData = da
					.filter(item => item.scheduleVos && item.scheduleVos.length > 0)
					.map(item => {
						return {
							date: year + '-' + parseInt(month) + '-' + item.day,
							scheduleVos: item.scheduleVos
						};
					});
				this.listData = [...newData];
				this.daylist = da.filter(item => item.scheduleVos && item.scheduleVos.length > 0).map(item => year + '-' + parseInt(month) + '-' + item.day);
				this.schelduleList = this.getListData(selectDate);
				console.log('日期' + JSON.stringify(this.daylist));
			});
		},
		// 滚动到底部加载更多
		loadMore() {
			this.getplanList();
		},

		handleScroll(e) {
			this.scrollTop = e.detail.scrollTop;
		},
		scrollToTop() {
			// 需要获取 scroll-view 实例并调用 scrollTo 方法
			this.$nextTick(() => {
				const query = uni.createSelectorQuery().in(this);
				query.select('scroll-view').boundingClientRect();
				query.exec(res => {
					if (res[0]) {
						res[0].node.scrollTo({
							top: 0,
							behavior: 'smooth'
						});
					}
				});
			});
		},
		backToTop() {
			uni.pageScrollTo({
				scrollTop: 0,
				duration: 300
			});
		}
	},
	onPageScroll(e) {
		this.scrollTop = e.scrollTop;
	}
};
</script>
<style scoped lang="scss">
.pageview {
	height: 100vh;
	background: #f7f7fc;
	//overflow: auto;

	.topwrap {
		background: $u-primary;
		padding-bottom: 60rpx;

		.welcome {
			color: #fff;
			padding: 20rpx;
			font-size: 40rpx;
		}
	}

	.scroll-view {
		flex: 1;
		margin-top: -60rpx;
		overflow: auto;
	}

	.main {
		margin-top: -60rpx;
		min-height: 0;
		overflow: auto;
	}

	.calendarbox {
		border-radius: 10rpx;
		padding: 0 20rpx;
		background: #fff;
	}

	.cu-title {
		padding: 0 20rpx;
		font-size: 36rpx;
		font-weight: 600;
	}
}

.scheldule {
	margin: 10upx 20upx;

	.scheldule-item {
		padding: 20rpx 20upx;
		background: #fff;
		margin: 10upx 0;
		color: #666;
		border-radius: 10rpx;
	}
}

.loading-status {
	padding: 30rpx;
	text-align: center;
	color: #999;
	font-size: 26rpx;

	.no-more {
		display: block;
		color: #ccc;
		padding: 20rpx 0;
	}

	.error {
		color: #ff5a5f;
		text-decoration: underline;
	}
}
</style>
